import {Injectable} from '@angular/core';
import {Setting} from '../setting/setting';
import {App} from "ionic-angular";
import {Common} from "./common";

@Injectable()
export class RequestFilter {
  private loading: any;

  constructor(private appCtrl: App, private common: Common) {
  }

  /**
   * 过滤请求参数
   * @param config
   * mask: false,//是否需要显示遮罩层
   * auth: false,//是否需要权限验证
   * shtml: false,//是否需要添加.shtml后缀
   */
  requestConfigFilter(config) {
    const me = this;
    if (!config.hasOwnProperty('shtml')) config.url += '.shtml'; //如果没有指定shtml参数为false，则会为请求URL添加.shtml后缀
    let async = true, method = 'post', dataType = 'json';
    if (!config.hasOwnProperty('async')) config.async = async;
    if (!config.method) config.method = method;
    if (!config.dataType) config.dataType = dataType;
    // if (!config.timeout) config.timeout = timeout;
    let token = localStorage.getItem(Setting.storage.authorizationToken);
    // 当没有单独指定headers，并且auth参数不为空且不为false，并且token存在，给请求加headers
    if (!config.headers && !(config.hasOwnProperty('auth') && !config.auth) && token) {
      config.headers = {'Authorization': token};
    }//给请求头加token


    //提交前显示遮罩层
    config.beforeSend = function (xhr) {
      if (config.mask === true) {
        me.loading = me.common.loading('');
        me.loading.present();
      }//显示遮罩层
    };

    //设置全局ajax登录拦截
    let success = config.success;
    config.success = function (result, status, xhr) {
      if (config.mask === true) me.loading.dismiss();//隐藏遮罩层
      //每次请求成功都更新本地缓存的token
      if (xhr.getResponseHeader('token')) {
        localStorage.setItem(Setting.storage.authorizationToken, xhr.getResponseHeader('token'));
      }
      me.responseFilter(config, result);//处理返回信息
      if (typeof success === 'function') success(result, status, xhr);
    };

    let error = config.error;
    config.error = function (result, status, xhr) {
      if (config.mask === true) me.loading.dismiss();//隐藏遮罩层
      //回调
      me.responseFilter(config, result);//处理返回信息
      /*if (status == 'timeout') {
        me.common.toast('请求超时,请稍后再试')
      }else */
      me.common.toast('请求失败');//失败提示
      if (typeof error === 'function') error(result, status, xhr);
    };

    /**
     * 其他情况访问结束处理
     */
    /*config.complete = function (result, status, xhr) {
      if (status == 'timeout') {
        me.common.toast('请求超时,请稍后再试')
      }
    };*/
    return config;
  }

  /**
   * 请求结果处理
   */
  responseFilter(config, result) {
    //登陆过期给出提示
    if (result.code && result.code == Setting.ENUM.HttpCodesEnum.logout) {//如果token过期
      this.common.toast('登陆过期');
      localStorage.removeItem(Setting.storage.authorizationToken);//移除token，跳转到登录页
      let curRoote = location.hash;
      if (curRoote.indexOf('login') === -1) this.appCtrl.getRootNav().push('LoginPage');
    } else if (!result.success && !config.noErrTip) {
      //请求失败提示info
      this.common.toast(result.info);
    }
  }
}
